<template>
  <el-dialog title="选择店铺位置" :visible.sync="dialogVisible" width="80%">
    <div class="map-container">
      <!-- 百度地图容器 -->
      <baidu-map
        class="bm-view"
        :center="mapCenter"
        :zoom="15"
        @dblclick="handleMapClick"
        @ready="mapInit"
      >
        <!-- 自动定位组件 -->
        <bm-geolocation
          anchor="BMAP_ANCHOR_BOTTOM_RIGHT"
          :showAddressBar="true"
          :autoLocation="true"
          @locationSuccess="handleLocationSuccess"
        />

        <!-- 搜索框 -->
        <bm-local-search
          ref="localSearch"
          :keyword="searchKeyword"
          :auto-viewport="true"
          @searchcomplete="handleSearchComplete"
        />

        <!-- 标记点 -->
        <bm-marker
          v-if="currentPoint"
          :position="currentPoint"
          :dragging="true"
          animation="BMAP_ANIMATION_BOUNCE"
        />
      </baidu-map>

      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索店铺/地址"
          @keyup.enter="triggerSearch"
        >
          <el-button slot="append" @click="triggerSearch">搜索</el-button>
        </el-input>
      </div>
    </div>

    <div slot="footer">
     
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="confirmSelection">确认选择</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {
  BaiduMap,
  BmMarker,
  BmLocalSearch,
  BmGeolocation,
} from "vue-baidu-map";

export default {
  components: {
    BaiduMap,
    BmMarker,
    BmLocalSearch,
    BmGeolocation,
  },
  props: {
    value: Boolean,
  },
  data() {
    return {
        showSearchBox:true,
      dialogVisible: this.value,
      mapCenter: { lng: 116.404, lat: 39.915 }, // 默认中心点
      currentPoint: null,
      searchKeyword: "",
      addressInfo: {
        name: "",
        address: "",
        point: { lng: 116.404, lat: 39.915 },
      },
    };
  },
  watch: {
    value(val) {
      this.dialogVisible = val;
    },
    dialogVisible(val) {
      this.$emit("input", val);
    },
  },
  methods: {
    handleSelectItem(item) {
      // 清除旧标记
      this.map.clearOverlays();

      // 创建新标记
      const point = new BMap.Point(item.point.lng, item.point.lat);
      const marker = new BMap.Marker(point);
      this.map.addOverlay(marker);

      // 更新地图中心点
      this.map.panTo(point);

      // 隐藏搜索框和列表
      this.showSearchBox = false;
    },
    handleLocationSuccess(result) {
      // 1. 提取定位结果
      const position = result.point;

      // 2. 更新地图中心点[3](@ref)
      this.mapCenter = {
        lng: position.lng,
        lat: position.lat,
      };

      // 3. 保存当前定位点（用于标记显示）
      this.currentPoint = position;

      // 4. 执行逆向地理编码[6,7](@ref)
      this.reverseGeocode(position);

      // 5. 更新初始化状态（控制标记显示）
      this.initLocation = true;

      // 调试日志
      console.log("定位成功：", {
        coordinates: position,
        accuracy: result.accuracy,
      });
    },

    handleSearchComplete(results) {
      if (results && results.getResults().length) {
        const poi = results.getResults()[0];
        this.currentPoint = poi.point;
        this.mapCenter = poi.point;
        // 更新地址信息（参考网页[5](@ref)的逆向地理编码实现）
        this.reverseGeocode(poi.point);
      } else {
        if (!results || results.getResults().length === 0) {
          this.$message.error("未找到相关地点");
          return;
        }
      }
    },
    triggerSearch() {
      if (!this.searchKeyword.trim()) return;
      // 强制触发BmLocalSearch组件更新（关键步骤）
      this.$nextTick(() => {
        this.$refs.localSearch.search(this.searchKeyword);
      });
    },
    mapInit({ BMap, map }) {
      this.BMap = BMap;
      this.map = map;
    },

    // 地图双击事件
    handleMapClick(e) {
      this.currentPoint = e.point;
      this.reverseGeocode(e.point);
    },

    // 逆地理编码获取地址详情
    async reverseGeocode(point) {
      const geocoder = new this.BMap.Geocoder();
      geocoder.getLocation(point, (result) => {
        if (result) {
          this.addressInfo = {
            name: result.business || result.address,
            address: result.address,
            point: point,
          };
        }
      });
    },

    // 搜索完成回调
    handleSearchComplete(results) {
      if (results && results.getResults().length) {
        const poi = results.getResults()[0];
        this.currentPoint = poi.point;
        this.mapCenter = poi.point;
        this.addressInfo = {
          name: poi.title,
          address: poi.address,
          point: poi.point,
        };
      }
    },

    // 确认选择
    confirmSelection() {
      if (this.addressInfo.point) {
        this.$emit("confirm", this.addressInfo);
        this.dialogVisible = false;
      } else {
        this.$message.warning("请先选择位置");
      }
    },
  },
  
};
</script>

<style scoped>
.map-container {
  position: relative;
  height: 600px;
}

.bm-view {
  width: 100%;
  height: 100%;
}

.search-bar {
  position: absolute;
  top: 20px;
  left: 20px;
  z-index: 999;
  width: 300px;
  background: rgba(255, 255, 255, 0.8);
  padding: 10px;
  border-radius: 4px;
}
</style>